//
//  LyNetWorkingTools.swift
//  Swift封装网络工具类单例
//
//  Created by 蒋琪 on 2017/6/7.
//  Copyright © 2017年 jq. All rights reserved.
//

import UIKit
import AFNetworking

//MARK: -枚举
enum HTTPMethod{
    case POST
    case GET
}

class LyNetWorkingTools: AFHTTPSessionManager {
    
    static let sharedTools:LyNetWorkingTools = {
    
        let tools = LyNetWorkingTools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        return tools
    }()
    
    
    /// 核心方法
    ///
    /// - Parameters:
    ///   - method: 请求方式
    ///   - urlString: 请求地址
    ///   - parameters: 参数
    ///   - finished: 成功后的回调
    func request(method:HTTPMethod,urlString:String,parameters:Any?,finished:@escaping (Any?,Error?) -> ()) {
//        <#T##((URLSessionDataTask, Any?) -> Void)?##((URLSessionDataTask, Any?) -> Void)?##(URLSessionDataTask, Any?) -> Void#>
        //成功的回调
        let successCallback = { (task:URLSessionDataTask?,responseObject:Any?) -> () in
        
            finished(responseObject,nil)
        }
        
//        <#T##((URLSessionDataTask?, Error) -> Void)?##((URLSessionDataTask?, Error) -> Void)?##(URLSessionDataTask?, Error) -> Void#>
        //失败的回调
        let failureCallback = {(task:URLSessionDataTask?,error:Error) -> () in
        
            finished(nil, error)
        }
        
        
        if method == .GET {
            get(urlString, parameters: parameters, progress: nil, success: successCallback, failure: failureCallback)
        }else{
            post(urlString, parameters: parameters, progress: nil, success: successCallback, failure: failureCallback)
        }
    }
    
}
